﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using e.Store.Domain;
using e.Store.Domain.Repositories;
using e.Store.Model.Entities;

namespace e.Store.Web.Controllers
{
    public class AdministratorController : Controller
    {

        IUnitOfWork _IUWork;

        public AdministratorController()
        {
            _IUWork = new UnitOfWorkcs();
        }

        public AdministratorController(IUnitOfWork _IUnit)
        {
            _IUWork = _IUnit;
        }

        //
        // GET: /Administrator/

        public ActionResult Index()
        {
            return View();
        }


        #region MANAGE USERS

        //Users
        public ActionResult Users()
        {
            return View();
        }

        public ActionResult EditUser(long id)
        {

            User user = _IUWork.Repository<User>().FindById(id);

            List<Role> lstRole = _IUWork.Repository<Role>().Query().Get().Where(c => c.Active == true).ToList();

            ViewBag.RoleList = lstRole;

            return View("UserCRUD", user);

        }

        public ActionResult AddUser()
        {

            List<Role> lstRole = _IUWork.Repository<Role>().Query().Get().Where(c => c.Active == true).ToList();

            ViewBag.RoleList = lstRole;

            return View("UserCRUD");
        }

        [HttpPost]
        public ActionResult AddAndUpdateUser(User objUser)
        {
            try
            {
                objUser.CreatedBy = 1;

                if (objUser != null && objUser.UserOID > 0)
                {
                    User u = _IUWork.Repository<User>().FindById(objUser.UserOID);

                    u.Active = objUser.Active;
                    u.Address = objUser.Address;
                    u.CreatedBy = objUser.CreatedBy;
                    u.EmailID = objUser.EmailID;
                    u.FirstName = objUser.FirstName;
                    u.LastName = objUser.LastName;
                    u.MobileNum = objUser.MobileNum;
                    if (!string.IsNullOrEmpty(objUser.Password))
                    {
                        u.Password = objUser.Password;
                    }
                    u.PhoneNum = objUser.PhoneNum;
                    u.RoleOID = objUser.RoleOID;
                    u.Username = objUser.Username;

                    _IUWork.Repository<User>().Update(u);
                    _IUWork.Save();

                    TempData["Result"] = "Success!:User updated successfully.";
                }
                else
                {
                    objUser.CreatedDate = DateTime.Now;

                    _IUWork.Repository<User>().Insert(objUser);
                    _IUWork.Save();

                    TempData["Result"] = "Success!:User added successfully.";
                }
            }
            catch (Exception)
            {
                TempData["Result"] = "Error!:Please try later! An error has occurred while processing your request.";
            }

            return RedirectToAction("Users");
        }

        public ActionResult LoadUserGridData()
        {
            UserRepository proRepo = _IUWork.ExtRepositoryFor<UserRepository>();

            List<LoadAllUsersResult> lstUsers = proRepo.LoadAllUsers();

            return PartialView("_UserGrid", lstUsers);
        }

        //CheckUsername

        [HttpPost]
        public JsonResult CheckUsername(string username)
        {
            try
            {
                User objUser = _IUWork.Repository<User>().Query().Get().Where(c => c.Username.Trim().ToLower() == username.Trim().ToLower()).FirstOrDefault();

                bool userExists = false;
                if (objUser != null)
                {
                    userExists = true;
                }
                return Json(new { Success = userExists, Message = "Username already exists. Please use a unique username." }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new { Success = false, Message = "Please try later! An error has occurred while processing your request." }, JsonRequestBehavior.AllowGet);
            }
        }


        #endregion


        #region MANAGE ROLES

        //Roles
        public ActionResult EditRole(long id)
        {

            Role role = _IUWork.Repository<Role>().FindById(id);

            MenuRepository menuRepo = _IUWork.ExtRepositoryFor<MenuRepository>();

            List<Menu> lstMenu = menuRepo.GetAllMenus();

            ViewBag.SelectedValues = role.RefMenuRoles.Select(c => c.MenuOID);

            ViewBag.Menulist = new MultiSelectList(lstMenu, "MenuOID", "MenuName", null);

            return View("RoleCrud", role);
        }

        public ActionResult AddRole()
        {
            MenuRepository menuRepo = _IUWork.ExtRepositoryFor<MenuRepository>();

            List<Menu> lstMenu = menuRepo.GetAllMenus();

            ViewBag.SelectedValues = null;

            ViewBag.Menulist = new MultiSelectList(lstMenu, "MenuOID", "MenuName", null);

            return View("RoleCrud");
        }

        //Roles
        public ActionResult Roles()
        {
            MenuRepository menuRepo = _IUWork.ExtRepositoryFor<MenuRepository>();

            List<Menu> lstMenu = menuRepo.GetAllMenus();

            ViewBag.SelectedValues = null;

            ViewBag.Menulist = new MultiSelectList(lstMenu, "MenuOID", "MenuName", null);

            return View();
        }

        [HttpPost]
        public ActionResult AddAndUpdateRole(Role role, List<string> RefMenuRoles)
        {
            try
            {
                if (role != null && role.RoleOID > 0)
                {
                    _IUWork.Repository<Role>().Update(role);
                    _IUWork.Save();

                    if (role.RoleOID > 0)
                    {
                        List<RefMenuRole> lstrefRoles = _IUWork.Repository<RefMenuRole>().Query().Get().Where(c => c.RoleOID == role.RoleOID).ToList();
                        foreach (RefMenuRole iRole in lstrefRoles)
                        {
                            _IUWork.Repository<RefMenuRole>().Delete(iRole);
                        }

                        RefMenuRole refMenuRole = null;
                        foreach (string menu in RefMenuRoles)
                        {
                            refMenuRole = new RefMenuRole();
                            refMenuRole.MenuOID = Convert.ToInt64(menu);
                            refMenuRole.RoleOID = role.RoleOID;

                            _IUWork.Repository<RefMenuRole>().Insert(refMenuRole);
                            _IUWork.Save();
                        }
                    }

                    TempData["Result"] = "Success!:Role updated successfully.";
                }
                else
                {
                    _IUWork.Repository<Role>().Insert(role);
                    _IUWork.Save();

                    if (role.RoleOID > 0)
                    {
                        RefMenuRole refMenuRole = null;
                        foreach (string menu in RefMenuRoles)
                        {
                            refMenuRole = new RefMenuRole();
                            refMenuRole.MenuOID = Convert.ToInt64(menu);
                            refMenuRole.RoleOID = role.RoleOID;

                            _IUWork.Repository<RefMenuRole>().Insert(refMenuRole);
                            _IUWork.Save();
                        }
                    }

                    TempData["Result"] = "Success!:Role added successfully.";
                }
            }
            catch (Exception)
            {
                TempData["Result"] = "Error!:Please try later! An error has occurred while processing your request.";
            }

            return RedirectToAction("Roles");
        }

        [HttpPost]
        public JsonResult CheckRole(string roleName)
        {
            try
            {
                Role objRole = _IUWork.Repository<Role>().Query().Get().Where(c => c.RoleName.Trim().ToLower() == roleName.Trim().ToLower()).FirstOrDefault();

                bool roleExists = false;
                if (objRole != null)
                {
                    roleExists = true;
                }
                return Json(new { Success = roleExists, Message = "Role code already exists. Please use a unique role name." }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new { Success = false, Message = "Please try later! An error has occurred while processing your request." }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult LoadRoleGridData()
        {
            List<Role> lstRole = _IUWork.Repository<Role>().Query().Get().ToList();

            return PartialView("_RoleGrid", lstRole);
        }

        #endregion
    }

}
